/* ===================================================
 * manage.leader.form.js v1.0.0
 * ===================================================
 * This javascript file contains functions to create form,
 * add form , delete form etc.
 * ========================================================== */
		
	function updateVoyageInfo(voyageField){
		$(document).ready(function() {
			$.ajax({  
				type: "POST",  
				url: "GetVoyage",
				data: {voyageId:voyageField.value},
				crossDomain: false,
				async : true,
		   	 	success: function(response) {
		   	 		var jsonList = response;
					
					$("#cutoff").val(jsonList.cutOffDate);
					$("#etd").val(jsonList.etdDate);
            	},
		   		error: function(result){
		   			alert('Error occured while retrieving value of Vessel');
		    	}
			});
		});
	}
	
	function updateModeDiv()
	{
		$(document).ready(function() {
			
			var modeid = $("#modeid").val();
			
			if (modeid == 62){
				$('#emptyPickupLabel').text("Handover To");
				$('#carrierLabel').text("Stuff By");
			}
			else if(modeid == 51 || modeid == 32){
				$('#emptyPickupLabel').text("Empty Pick-Up");
				$('#carrierLabel').text("Carrier");
			}
		});
	};

	function updateHazCargoDiv(){
		
		$(document).ready(function() {
			var cargotypeid = $("#cargotypeid").val();
						
			if( cargotypeid == 57){
				$("#hazConsignmentTable").show();
				$("#hazrefcolor").css('background-color', '#E91100');
				$('#reeferConsignmentTable').hide();

//				if ( !$('table#reeferConsignmentTable').is(':visible'))
//					$('table#reeferConsignmentTable').toggle();
			}
			else if( cargotypeid == 70){
//				$('table#hazConsignmentTable').toggle();
//				$('table#reeferConsignmentTable').is(':visible');
				
				// Working on IE and Chrome only
				$("#hazConsignmentTable").hide();
				$('#reeferConsignmentTable').show();
				$("#hazrefcolor").css('background-color', '#009ACD');
			}
			else if (cargotypeid == 55 || cargotypeid == 65 || cargotypeid == 66){
				$("#hazConsignmentTable").hide();
				$('#reeferConsignmentTable').hide();
				$("#hazrefcolor").css('background-color', '#FFFFFF');
			}
			else
			{
				$("#hazConsignmentTable").hide();
				$('#reeferConsignmentTable').hide();
				$("#hazrefcolor").css('background-color', '#FFFFFF');
			}
		});
	}
	
	function checkDoorDelivery()
	{
		$(document).ready(function() {
			
			//var modeid = $("#chkDoorDelivery").val();
			
			if ($('#chkDoorDelivery').is(':checked')) {
			    $("#doordelivery").show();
			}
			else {
			    $("#doordelivery").hide();
			}
		});
	};
	
	function populateDepartmentsForBranches(ids)
	{
		var listItems = "";
		if(typeof ids == "undefined" || ids == null)
		{
			$('#departmentId').html(listItems);
			$("#departmentId").chosen();
			return;
		}
		
		$.ajax({
			type: "POST",  
			url: "GetDepartmentListForBranchList?sourceId="+ids,
			/*url: "GetDepartmentListForBranchList",
			 data:{
				sourceId:a
			},*/
			crossDomain: false,
			async : true,
	   	 	success:function(response) 
	   	 	{
	   	 		var branches = response.data;
	   	 		for(var i=0;i<branches.length;i++)
	   	 		{
	   	 			var branchname = branches[i].branchname;
	   	 			var departments = branches[i].departments;
	   	 		
	   	 			listItems += '<optgroup label="'+branchname+'">';
	   	 			for(var j=0;j<departments.length;j++)
	   	 			{
	   	 				listItems += "<option value='" + departments[j].departmentid + "' >" + departments[j].departmentname + "</option>";
	   	 			}	
	   	 			listItems += '</optgroup>';
	   	 		}
	   	 		$('#departmentId').html(listItems);
	   	 		$("#departmentId").chosen();
        	},
	   		error:function(result)
	   		{
	   			$('#departmentId').html(listItems);
	   	 		$("#departmentId").chosen();
	    	}
		});
	};
	
	function renderDependentCombo (formValue,urlaction,dependentFieldId,selectedValue,events){
		$(document).ready(function() {
				$.ajax({  
					type: "POST",  
					url: urlaction,
					data: {sourceId:formValue},
					crossDomain: false,
					async : true,
			   	 	success: function(response) {
			   	 		
			   	 		var isMultiSelect = typeof $("#"+dependentFieldId).attr("multiple") !== 'undefined';
			   	 		var jsonList = response;
			   	 	    var listItems= "";
			   	 	    if(!isMultiSelect)
			   	 	    {
			   	 	    	listItems= "<option value=''>--SELECT--</option>";			   	 	    	
			   	 	    }
			   	 		if(jsonList != null)
			   	 		{
			   	 			for (var i = 0; i < jsonList.length; i++)
			   	 			{
				   	 			listItems+= "<option value='" + jsonList[i].fieldId + "'>" + jsonList[i].fieldname + "</option>";
					        }
			   	 		}
			   	 		
			       		$("#"+dependentFieldId).html(listItems);
			       		
			       		if(isMultiSelect)
			       		{
							$("#"+dependentFieldId).chosen();
			       		}
			       		
			       		if(selectedValue != '')
			       		{
			       			$("#"+dependentFieldId).val(selectedValue).trigger('change');
		   	 			}
			       		
			       		if( typeof events !== "undefined" && events !== null)
			       		{
			       			if(events.success)
			       			{
			       				events.success(response,true);
			       			}
			       		}
	            	},
			   		error: function(result){
			   			var listItems= "<option value=''>--SELECT--</option>";
			   			$("#"+dependentFieldId).html(listItems);
			    	}
				});
		} );
	};
	
	function formatDate(field) {

		var fieldValue = field.value;

		if (!hasInvalidChar(fieldValue, "/")) {
			if (fieldValue.length == 6) {
				var year = fieldValue.substring(4, 6);
				if (parseInt(year) > 30) {
					var newValue = fieldValue.substring(0, 2) + "/" + fieldValue.substring(2, 4) + "/19" + fieldValue.substring(4, 6);
					field.value = newValue;
				} else {
					var newValue = fieldValue.substring(0, 2) + "/" + fieldValue.substring(2, 4) + "/20" + fieldValue.substring(4, 6);
					field.value = newValue;
				}
			} else if (fieldValue.length == 7) {
				var newValue = "0" + fieldValue.substring(0, 1) + "/" + fieldValue.substring(1, 3) + "/" + fieldValue.substring(3, 7);
				field.value = newValue;
			} //end of else if
			else if (fieldValue.length == 8) {
				var newValue = fieldValue.substring(0, 2) + "/" + fieldValue.substring(2, 4) + "/" + fieldValue.substring(4, 8);
				field.value = newValue;
			} //end of else if
		} else {
			if (fieldValue.length == 8) {
				var spl = fieldValue.split("\/");
				var yrs = spl[2];
				var month = spl[0];
				var day = spl[1];
				if (yrs.length == 4) {
					field.value = "0" + month + "/0" + day + "/" + yrs;
				} else {
					var century = fieldValue.substring(6, 8);
					if (century > 30)
						field.value = fieldValue.substring(0, 6) + "19" + fieldValue.substring(6, 8);
					else
						field.value = fieldValue.substring(0, 6) + "20" + fieldValue.substring(6, 8);
				}

			}
		}
		//has valid characters		
	} //end of function - formatDate
	
	function LTrim(txtString) {
		ctr = 0;
		while (ctr < txtString.length && (txtString.substring(ctr, ctr + 1) == " ")) {
			ctr = ctr + 1;
		}
		return txtString.substring(ctr);
	}

	// returns the string after deleting the leading spaces

	function RTrim(txtString) {
		ctr = txtString.length;
		while (ctr > 0 && (txtString.substring(ctr, ctr - 1) == " ")) {
			ctr = ctr - 1;
		}
		return txtString.substring(0, ctr);
	}

	//returns the string after deleting the leading and trailing spaces

	function checkTrim(txtString) {
		txtString = LTrim(txtString);
		txtString = RTrim(txtString);
		return txtString;
	}

	//Validation for field which should not be empty
	function isEmpty(fieldname,fieldvalue)
	{
		
		var str=checkTrim(fieldvalue);
		if(str.length==0)
		{
			alert(fieldname + ' can not be empty ');
			return true;
		}
		return false;
	}

	//return false if it has invalid characters(validation for invalid characters)

	function hasInvalidChar(fieldvalue, charToMatch) {

		var str = fieldvalue;
		//var valid=true;
		var str = checkTrim(str);
		var chars = charToMatch; //invalid characters
		for (i = 0; i < str.length; i++) {
			for (j = 0; j < chars.length; j++) {

				if (str.charAt(i) == chars.charAt(j)) {
					return true;
				}
			}
		}

		return false;
	}

	/**
 * Register various formatter on focus lost, officer popups and type ahead rule, 
 */
$(document).ready(function () {
        /**
         * All element id that contains text 'date' or 'Date' will have formatter
         * registered on focus lost. 
         */
        $("input[id*='date']").focusout(function (event) {
                formatDate(this);
            });
        
        $("input[id*='Date']").focusout(function (event) {
                formatDate(this);
            });
		
		$( "input[id*='Date']" ).datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd/mm/yy"
		});
		
		$( "input[id*='date']" ).datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd/mm/yy"
		});
});